﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SqlServer.Management.Smo;
using WBGDal;
using WBGModel;

namespace RecursosHumanos
{
    public partial class frmLogin : Form
    {
        public bool logado = false;
               
        public frmLogin()
        {
            InitializeComponent();
        }

        private void btnOpcao_Click(object sender, EventArgs e)
        {
            if (frmLogin.ActiveForm.Height == 250)
            {
                btnOpcao.Text = "Opção <<";
                frmLogin.ActiveForm.Height = 430;
                cbServer.Visible = true;
                cbDatabase.Visible = true;
                ckbAutenticacao.Visible = true;
                btnServer.Visible = true;
                txtSQLUser.Visible = true;
                txtSQLPassword.Visible = true;
                lbServidor.Visible = true;
                lbDatabase.Visible = true;
                lbSQLUsuario.Visible = true;
                lbSQLSenha.Visible = true;
            }
            else
            {
                cbServer.Visible = false;
                cbDatabase.Visible = false;
                ckbAutenticacao.Visible = false;
                btnServer.Visible = false;
                txtSQLUser.Visible = false;
                txtSQLPassword.Visible = false;
                lbServidor.Visible = false;
                lbDatabase.Visible = false;
                lbSQLUsuario.Visible = false;
                lbSQLSenha.Visible = false;
                frmLogin.ActiveForm.Height = 250;
                btnOpcao.Text = "Opção >>";
            }
        }

        private void btnCancelar_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void frmLogin_Load(object sender, EventArgs e)
        {
            txtUsuario.Focus();
        }

        private void CarregarServidor()
        {
            DataTable DtServers = SmoApplication.EnumAvailableSqlServers(false);
            foreach (DataRow Row in DtServers.Rows)
            {
                String SqlServerName = Row["Server"].ToString();
                if (Row["Instance"] != null && Row["Instance"].ToString().Length > 0)
                {
                    SqlServerName += @"\" + Row["Instance"].ToString();
                }

                cbServer.Items.Add(SqlServerName);
            }
        }

        private void ckbAutenticacao_CheckedChanged(object sender, EventArgs e)
        {
            if (ckbAutenticacao.Checked)
            {
                txtSQLUser.Enabled = false;
                txtSQLPassword.Enabled = false;
            }
            else
            {
                txtSQLUser.Enabled = true;
                txtSQLPassword.Enabled = true;
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            try
            {
                frmLogin.ActiveForm.Text = "Conectando no Servidor...";

                //Conexao.connectionStr = "Data Source = " + cbServer.Text + " ;" +
                //                                    " Initial Catalog = " + cbDatabase.Text + ";" +
                //                                    " Integrated Security = " + ckbAutenticacao.Checked.ToString() + ";" +
                //                                    " user = " + txtSQLUser.Text + ";" +
                //                                    " password = " + txtSQLPassword.Text;

                DalUsuario daoUsu = new DalUsuario();

                var lst = daoUsu.Listar("nome='" + txtUsuario.Text + "'");

                if (lst == null || lst.Count == 0)
                {
                    MessageBox.Show("Usuário ou senha inválidos.", "Aviso", MessageBoxButtons.OK); //Não localizou usuário.
                    return;
                }

                if (lst[0].senha.CompareTo(clsDalCriptografia.Encrypt(txtSenha.Text)) != 0)
                {
                    MessageBox.Show("Usuário ou senha inválidos.", "Aviso", MessageBoxButtons.OK); //Senha errada.
                    return;
                }
                else
                {
                    logado = true;
                    ModelConfig.usuarioLogado = txtUsuario.Text;
                    ModelUsuario usu = new DalUsuario().Listar("nome = '" + txtUsuario.Text + "'")[0];
                    usu.ultimoAcesso = DateTime.Now;
                    new DalUsuario().Alterar(usu);
                    this.Dispose();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Problema ao realizar o login.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void cbServer_SelectedIndexChanged(object sender, EventArgs e)
        {
            Server server = new Server();

            server.ConnectionContext.LoginSecure = ckbAutenticacao.Checked;
            server.ConnectionContext.Login = txtSQLUser.Text;
            server.ConnectionContext.Password = txtSQLPassword.Text;
            server.ConnectionContext.ServerInstance = cbServer.Text;
            server.ConnectionContext.Connect();
           
            foreach (Database item in server.Databases)
            {
                cbDatabase.Items.Add(item.Name); 
            }

            cbDatabase.DisplayMember = "Name";
        }

        private void txtSenha_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                btnOk_Click(sender, new EventArgs());
            }
        }

        private void btnServer_Click(object sender, EventArgs e)
        {
            cbServer.Text = "SELECIONE UMA INSTÂNCIA";
            cbDatabase.Text = "SELECIONE UM BANCO DE DADOS";

            CarregarServidor();
        }

        private void txtUsuario_Enter(object sender, EventArgs e)
        {
            txtUsuario.SelectionStart = 0;
            txtUsuario.SelectionLength = txtUsuario.Text.Length;
        }

        private void txtSenha_Enter(object sender, EventArgs e)
        {
            txtSenha.SelectionStart = 0;
            txtSenha.SelectionLength = txtSenha.Text.Length;
        }
    }
}
